<template>
  <div>
    <el-input
      ref="input"
      v-model="data"
      :placeholder="placeholder"
      clearable
      @focus="clickInput"
      @clear="clearData">
      <el-button slot="append" @click="openDialog">选择用户</el-button>
    </el-input>

    <el-dialog title="根据部门选择用户" :visible.sync="dialogVisible" width="60%" @close="handleClose" append-to-body>
      <div class="diaPart">
        <div class="deptPart">
          <el-tree
            class="filter-tree"
            node-key="deptId"
            :data="deptOptions"
            :props="defaultProps"
            :expand-on-click-node="false"
            :default-expand-all="defaultExpandAll"
            @node-click="clickDept"
            ref="tree">
          </el-tree>
        </div>
        <div class="userPart">
          <el-form :inline="true" :model="queryParam" class="demo-form-inline" size="small">
            <el-form-item label="用户名称">
              <el-input v-model="queryParam.userName" placeholder="请输入用户名称" clearable></el-input>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="searchForm">查询</el-button>
              <el-button @click="resetForm">重置</el-button>
            </el-form-item>
          </el-form>
          <el-table ref="tableData" v-loading="loading" :data="tableData" @select="changeUser" @select-all="changeAllUser">
            <el-table-column type="selection" width="55" align="center"/>
            <el-table-column prop="userName" label="用户账号" align="center"/>
            <el-table-column prop="nickName" label="用户姓名" align="center"/>
            <el-table-column label="性别" align="center">
              <template slot-scope="{row}">
                <span>{{row.sex == 0 ? '男' : row.sex == 1 ? '女' : '未知'}}</span>
              </template>
            </el-table-column>
            <el-table-column prop="phonenumber" label="手机" align="center"/>
            <el-table-column prop="address" label="部门" align="center">
              <template slot-scope="{row}">
                <span>{{!!row.dept ? row.dept.deptName : ''}}</span>
              </template>
            </el-table-column>
          </el-table>
          <pagination
            v-show="total>0"
            :total="total"
            :page.sync="queryParam.pageNum"
            :limit.sync="queryParam.pageSize"
            :background="false"
            @pagination="getUserForm"
          />
        </div>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitDept">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import request from '@/utils/request'
export default {
  name: 'selectDept',
  props:{
    value: {             // 绑定值
      type: String,
      default: ''
    },
    placeholder: {       // 默认提示语
      type: String,
      default: '请先选择用户'
    },
    defaultExpandAll: {  // 是否默认展开所有节点
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      data: '',
      dialogVisible: false,
      queryParam: {
        deptId: null,
        userName: null,
        pageNum: 1,
        pageSize: 10
      },
      total: 0,
      tableData: [],
      loading: false,
      deptOptions: [],
      defaultProps: {
        children: 'children',
        label: 'deptName'
      },
      checkAllUser: []
    };
  },
  created() {
    this.getUserForm(true)
  },
  methods: {
    openDialog() {
      this.dialogVisible = true
      this.getDeptTree()
      this.getUserForm(false)
    },
    clickDept(data) {
      this.queryParam.deptId = data.deptId
      this.queryParam.pageNum = 1
      this.getUserForm(false)
    },
    changeUser(val, row) {
      let selected = val.length && val.includes(row)
      if (selected) {
        this.checkAllUser.push(row);
      } else {
        for(let i in this.checkAllUser) {
          if(this.checkAllUser[i].userId == row.userId) {
            this.checkAllUser.splice(i, 1);
            break;
          }
        }
      }
    },
    changeAllUser(rows) {
      let checkUserIds = this.checkAllUser.map((item) => item.userId);
      // 当前页选中行的标记列表
      let pageUserIds = Array.isArray(rows)
        ? rows.map((item) => item.userId)
        : [];

      this.tableData.forEach((row) => {
        if (pageUserIds.includes(row.userId)) {
          if (!checkUserIds.includes(row.userId)) {
            this.checkAllUser.push(row);
          }
        } else if (checkUserIds.includes(row.userId)) {
          for(let i in this.checkAllUser) {
            if(this.checkAllUser[i].userId == row.userId) {
              this.checkAllUser.splice(i, 1);
              break;
            }
          }
        }
      });
    },
    submitDept() {
      if(this.checkAllUser.length > 0) {
        let tempName = [],tempKeys = []
        this.checkAllUser.forEach(item => {
          tempName.push(item.nickName)
          tempKeys.push(item.userId)
        })
        this.data = tempName.join()
        this.$emit('input', tempKeys.join());
        this.dialogVisible = false
      }else {
        this.$message({
          message: '请先选择用户',
          type: 'warning'
        });
      }
    },
    handleClose() {
      this.$refs.tableData.clearSelection()
      this.tableData = []
      this.total = 0
      this.queryParam = {
        deptId: null,
        userName: null,
        pageNum: 1,
        pageSize: 10
      }
      this.deptOptions = []
      this.checkAllUser = []
    },
    clickInput() {
      this.$refs.input.blur()
    },
    clearData() {
      this.$emit('input', '');
    },
    searchForm() {
      this.queryParam.pageNum = 1
      this.getUserForm(false)
    },
    resetForm() {
      this.queryParam = {
        deptId: null,
        userName: null,
        pageNum: 1,
        pageSize: 10
      }
      this.getUserForm(false)
    },
    getUserForm(isEcho) {
      this.loading = true
      request({
        url: '/system/user/list',
        method: 'get',
        params: this.queryParam
      }).then(res => {
        if (res.code == 200) {
          this.tableData = res.rows
          this.total = res.total
          if(isEcho && this.value) {
            let tempKeys = this.value.split(',')
            let tempName = []
            tempKeys.forEach(item => {
              for(let i in this.tableData) {
                if(this.tableData[i].userId == item) {
                  tempName.push(this.tableData[i].nickName)
                  this.checkAllUser.push(this.tableData[i])
                }
              }
            })
            this.data = tempName.join()
          }else if(this.checkAllUser.length > 0 && this.tableData.length > 0) {
            this.checkAllUser.forEach(item => {
              this.tableData.forEach(tableItem => {
                if(item.userId == tableItem.userId) {
                  this.$nextTick(() => {
                    this.$refs.tableData.toggleRowSelection(tableItem);
                  })
                }
              })
            })
          }
        }
      }).finally(() => {
        this.loading = false
      })
    },
    getDeptTree() {
      request({
        url: '/system/dept/listTree',
        method: 'get',
        params: {}
      }).then(res => {
        if (res.code == 200) {
          this.deptOptions = res.data
        }
      })
    }
  },
};
</script>

<style lang="scss" scoped>
.el-dialog__wrapper ::v-deep .el-dialog__body {
  padding: 0 15px !important;
}
.diaPart {
  background-color: #ECECEC;
  padding: 10px;
  display: flex;
  align-items: flex-start;
  .deptPart {
    width: 280px;
    padding: 15px;
    margin-right: 15px;
    background-color: #fff;
  }
  .userPart {
    flex: 1;
    background-color: #fff;
    padding: 15px;
  }
}
</style>
